10. Constructors

ND213 A09 Constructors

Constructors

Constructors are member functions of a class or struct that initialize an object. The Core Guidelines define a constructor) as:

constructor: an operation that initializes (“constructs”) an object. Typically a constructor establishes an invariant and often acquires resources needed for an object to be used (which are then typically released by a destructor).

A constructor can take arguments, which can be used to assign values to member variables.

class Date {
 public:
  Date(int d, int m, int y) {  // This is a constructor.
    Day(d);
  }
  int Day() const { return day_; }
  void Day(int d) {
    if (d >= 1 && d <= 31) day_ = d;
  }
  int Month() const { return month_; }
  void Month(int m) {
    if (m >= 1 && m <= 12) month_ = m;
  }
  int Year() const { return year_; }
  void Year(int y) { year_ = y; }

 private:
  int day_{1};
  int month_{1};
  int year_{0};
};

As you can see, a constructor is also able to call other member functions of the object it is constructing. In the example above, Date(int d, int m, int y) assigns a member variable by calling Day(int d).

Workspace

This section contains either a workspace (it can be a Jupyter Notebook workspace or an online code editor work space, etc.) and it cannot be automatically downloaded to be generated here. Please access the classroom with your account and manually download the workspace to your local machine. Note that for some courses, Udacity upload the workspace files onto https://github.com/udacity, so you may be able to download them there.

Workspace Information:

  • Default file path:
  • Workspace type: jupyter
  • Opened files (when workspace is loaded): n/a

Default Constructor

A class object is always initialized by calling a constructor. That might lead you to wonder how it is possible to initialize a class or structure that does not define any constructor at all.

For example:

class Date { 
  int day{1};
  int month{1};
  int year{0};
};

We can initialize an object of this class, even though this class does not explicitly define a constructor.

This is possible because of the default constructor. The compiler will define a default constructor, which accepts no arguments, for any class or structure that does not contain an explicitly-defined constructor.